package Thread;

import Http.HttpInterface;
import Shop.Item;
import Time.Time;
import amiguu.GUI.MainWin;
import amiguu.GUI.SettingsFrame;
import java.io.FileNotFoundException;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;

public class User extends Thread{
	
	Vector<Item> list;
	int shopId;
	private HttpInterface handler;
        private MainWin window;
        private SettingsFrame settings;
        private boolean run;
        private int profit;
        
	
	public User(String user, String pw) throws FileNotFoundException{
		handler = new HttpInterface(user,pw);
                profit=0;
                run = false;
	}
        
        public void applySettings(SettingsFrame sett){
            settings = sett;
        }
        
        public void setRun(boolean b){
            run = b;
        }
        
        public int login(){
            return handler.login();
        }
        
        public boolean isUserLoggedIn(){
            return handler.loggedIn();
        }
        
        public void setShop(int shop){        		
            try {
                shopId = shop;
                list = handler.getList(shop, 1000);
            } catch (FileNotFoundException ex) {
                    Logger.getLogger(User.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        
        public void setWindow(MainWin win){
            window = win;
        }
	
	public Item somethingGood(Vector<Item> stock){
		for(Item i:list){
			for(Item j:stock){
				if(i.equals(j)){
					if((i.getPrice()-j.getPrice())>= settings.getMinProfit()){
						j.setEstProfit(i.getPrice()-j.getPrice());
						return j;
					}
				}
			}
		}
		return null;
	}
	
	public double getRandSleep(double min, double max){            
            if(min==max){
                return min;
            }            
            else if(min>1)
                return (min + (double)(Math.random() * ((max - min-1) + 1)));
            else{
                double result;
                boolean found = false;
                result = Math.random();
                while(!found){
                    if((result<min)||(result>max))
                        result = Math.random();
                    else
                        found = true;
                }
                return result;
            }
	}
	
	private boolean checkBanned(){
		Vector<Item> stock = handler.refresh(21);
		if(stock.size()==0){
			return true;
		}
		return false;
	}
        
        public int getPrice(int price) {
		String num = String.valueOf(price);
		String a,b,result;
		a = num.substring(0,1);
		b = num.substring(1,2);
		result = "";
		if(num.length() <= 5){
			for(int i=0; i<num.length();i++){
				if((i%2) == 0){
					result += a;
				}
				else{
					result += b;
				}
			}
		}
		else{
			String c = num.substring(2,3);
			for(int i=0; i<num.length();i++){
				if((i%3) == 0){
					result += a;
				}
				else if((i%3) == 1){
						result += b;
						}
				else{
					result +=c;
				}				
			}
		}
		return Integer.parseInt(result);
	}
	
	public void run(){            
                
                
                String timeCurrent,timeEnd;
                boolean banned = false;
		while((!banned)&&(run)){
                        //everyTime tiene cada cuanto me voy a dormir
                        double everyTime = getRandSleep(settings.getEveryMinTime(),settings.getEveryMaxTime());
                        //sleepTime tiene cuantos mins me voy a dormir
                        double pauseMins = getRandSleep(settings.getPauseMinTime(),settings.getPauseMaxTime());                        
                        int checkBan = 0; 
                        timeCurrent = Time.getHrMinSec();
                        timeEnd = Time.addMinutes(timeCurrent,(int)everyTime); 
                        while((!banned)&&(run)&&(Time.getDifInMins(timeCurrent, timeEnd)>0))
			{				                               
				long sleepTime = Math.round(getRandSleep(settings.getMinTime(),settings.getMaxTime())*1000);
                                window.changeStatus(Time.getHrMinSec() +" Asleep for " + sleepTime);
				try {
					this.sleep(sleepTime);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				Vector<Item> stock = handler.refresh(shopId);                             
				Item toBuy = somethingGood(stock);	
				if(stock.size()==0){
					checkBan++;
				}
				if(checkBan==10){
					if(handler.loggedIn()){
						if(checkBanned()){
							banned = true;
							window.appendTextLog("Account is now Restock Banned");                                                    
						}
						else{
							checkBan=0;
						}
					}
					else{
						System.err.println("Relogie");
						handler.login();
					}
				}				
				if (toBuy != null){
                                        window.appendTextLog("Trying to buy "+ toBuy.getName());					
                                        sleepTime = Math.round(getRandSleep(settings.getMinTime1(),settings.getMaxTime1())*1000);
                                        try {
                                            this.sleep(sleepTime);
                                        } catch (InterruptedException e) {
                                            e.printStackTrace();
                                        }
                                        toBuy.setPrice(getPrice(toBuy.getPrice()));
					String result = handler.buyItem(toBuy);
                                        window.appendTextLog(result);
                                        if(result.contains("Bought For")){
                                            profit+=toBuy.getEstProfit();
                                            window.setProfit(profit);
                                        }
				}
                                timeCurrent = Time.getHrMinSec();
				
			}
			try {  
                                if(run){
                                    window.appendTextLog("Pausing for: " + Math.round(pauseMins));
                                    window.changeStatus("Pause for: "+ Math.round(pauseMins));
                                    this.sleep((long)pauseMins*60*1000);
                                    window.appendTextLog("Woke up");
                                }
                                else{
                                    window.appendTextLog("Amiguu Stopped");
                                }
			} catch (InterruptedException e1) {
				e1.printStackTrace();
			}
		}
		
	}	
}
